<template>
	<view class="box">
		<canvas  :hidpi="true" :style="{'width':css.width+'px','height':css.height+'px'}" canvas-id="firstCanvas" id="firstCanvas"></canvas>
		<qrcode v-if="painting.type=='text'" :text="painting.qrcode" @getLink="setLink"></qrcode>
		<!-- <img :src="poster" style="position: fixed;top: 0;left: 0; width: 750rpx;height: 900rpx;"></img> -->
		<view class="loading_box" v-if="GetLoading">
			<view>
				<span>{{loadingText}}</span>
				 <div class="loading" >
				     <div class="loading-1 loading-item"></div>
				     <div class="loading-2 loading-item"></div>
				     <div class="loading-3 loading-item"></div>
				     <div class="loading-4 loading-item"></div>
				 </div>
			</view>
		</view>
	</view>
</template>

<script>
	import qrcode from '@/components/yz-qr/yz-qr.vue'
	import { setShare, shareApp } from '@/until/QFH5.js'
	import {mapGetters} from 'vuex'
	export default {
		components:{qrcode},
		computed: {
			...mapGetters({siteinfo:'siteinfo'})
		},
		props: {
			painting: {
				type: Object,
				default:()=>{
					// uni提供的单位是px  不是rpx ！！！ 请根据图片分辨率自行调整位置
					return{
						background:'',//海报背景
						qrcode:'',//二维码
						qrleft: 750,//左距离(px)or x%
						qrtop: 450,//顶部距离(px) x%
						qrwidth: 450,//二维码宽高（px）
						qrheight: 450,
						type:'image'
					}
				}
			},
		},
		data() {
			return {
				ctx: "",
				image: require('@/static/guess/bag.png'),
				canvasImg: '',
				imgUrl:'',
				css: {
					width: 800,
					height: 450
				},//画布高度
				// siteinfo:{},//7牛上传地址
				size:300,//引用二维码插件的二维码大小
				bgc: 'rgba(200, 200, 200, 0.1)',//对比
				link:null,//生成的二维码,
				poster:'',
				GetLoading:true,
				loadingText:'海报生成中',
			}
		},
		methods: {
			setLink(val){
				this.link = val
			},
			async getImg(){
				let _this = this
				let ctx = uni.createCanvasContext("firstCanvas")
				let res = await this.downloadFile( _this.painting.background,'背景图片下载')
				if(res.statusCode!=200){
					_this.GetLoading=false
					console.log(res)
					uni.showToast({
						title:'背景图片异常:'+res.statusCode,
						icon:'none'
					})
					return
				}
				let bg = await _this.getImageInfo(res)
				_this.css = {
					width: bg.width,
					height: bg.height
				}
				
				if(_this.painting.qrleft.indexOf('%')>-1){
					let num = _this.painting.qrleft.replace(/%/,"")/100
					_this.painting.qrleft = Math.floor(bg.width*num)
				}
				if(_this.painting.qrtop.indexOf('%')>-1){
					let num = _this.painting.qrtop.replace(/%/,"")/100
					_this.painting.qrtop = Math.floor(bg.height*num)
				}
				console.log(_this.painting.qrleft,_this.painting.qrtop)
				ctx.drawImage(bg.path, 0, 0, bg.width, bg.height);
				if(_this.painting.type=='image'){
					if(_this.painting.qrcode==null || _this.painting.qrcode==""){
						_this.GetLoading=false
						uni.showToast({
							title:'平台二维码发生异常',
							icon:'none'
						})
						console.log('二维码',_this.painting)
						return
					}
					let qrcode = await this.downloadFile( _this.painting.qrcode,'下载二维码')
					setTimeout(()=>{
						//背景图太大等一下 不然uni画不完
						ctx.drawImage(qrcode.tempFilePath, Number(_this.painting.qrleft), Number(_this.painting.qrtop), Number(_this.painting.qrwidth), Number(_this.painting.qrheight))
						ctx.draw(true, () => {
							console.log('获取二维码图片成功')
							setTimeout(() => {
								//立即执行ios拉不到回调
								_this.getImage()
								
							}, 150)
						})
					},300)
				}else if(_this.painting.type=='text'){
					// if(_this.link!=null || _this.link==null){
						setTimeout(()=>{
							ctx.drawImage(_this.link,parseInt( _this.painting.qrleft),parseInt(_this.painting.qrtop),parseInt( _this.painting.qrwidth),parseInt( _this.painting.qrheight))
							ctx.draw(false, () => {
								setTimeout(() => {
									_this.getImage()
								},150)
																
							})
						},300)
					// }else{
					// 	uni.showToast({
					// 		title:'转换文本为空：'+this.link,
					// 		icon:'none',
					// 		duration:3000
					// 	})
					// 	_this.GetLoading = false
					// }
				}
			},
			//生产图片
			getImage() {
				let _this = this
				uni.canvasToTempFilePath({
					canvasId: "firstCanvas",
					fileType: "jpg",
					quality: 1,
					destWidth: _this.css.width,
					destHeight: _this.css.height,
					success: function(e) {
						_this.canvasImg = e.tempFilePath
						
						_this.GetLoading = false
						_this.getUrl().then(res=>{
							_this.$emit('Url',e.tempFilePath)
							// console.log('画完图片 释放',res)
							// _this.GetLoading = false
							// QFH5.saveImage(res)
							// setShare(res)
							
							// shareApp()
						})
					},
					fail: function(e) {
						uni.showToast({
							title: e
						})
					}
				})
			},
			//提取7牛的url
			getUrl() {
				let _this = this
				return new Promise((resolve, reject) => {
					var pic = this.canvasImg.split(";base64,")[1] // 截取data:image/png;base64,之后的base64
					var url = _this.siteinfo.zoneHost + "/putb64/-1"; //非华东空间需要根据注意事项 1 修改上传域名
					var xhr = new XMLHttpRequest();
					var xhrget = new XMLHttpRequest();
					var obj;
					xhr.open("POST", url, true);
					xhr.setRequestHeader("Content-Type", "image/png");
					xhr.setRequestHeader("Authorization", 'UpToken ' + _this.siteinfo.qiniuToken);
					xhr.send(pic);
					xhr.onreadystatechange = () => {
						if (xhr.readyState == 4) {
							let info = JSON.parse(xhr.responseText)
							this.imgUrl = info.domain + info.key
							resolve(info.domain + info.key)
						}
					}
				});
			},
			//下载文件
			downloadFile(url,errText=''){
				return new Promise((resolve,recject)=>{
					uni.downloadFile({
						url: url,
						success(res) {
							resolve(res)
						},
						fail(e){
							this.GetLoading=false
							console.log('fail',e)
							uni.showToast({
								title:errText+'：'+JSON.stringify(e),
								icon:'none'
							})
						}
					})
				})
			},
			//获取图片信息
			getImageInfo(data){
				return new Promise((resolve,recject)=>{
					uni.getImageInfo({
						src:data.tempFilePath,
						success(res) {
							resolve(res)
						},
						fail(e){
							this.GetLoading=false
							console.log('fail',e)
							uni.showToast({
								title:'读取图片信息异常：'+JSON.stringify(e)
							})
						}
					})	
				})
			},
		},
		mounted() {
			let _this = this
			this.getImg()
			
		},
		watch:{
			link:{
				handler(newVal,oldVal){

				},deep:true
			}
		}
	}
</script>

<style lang="scss" scoped>
	// .box{
	// 	position: fixed;
	// 	top: 0;
	// 	left: 0;
		
	// }
	.loading_box{
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
		width: 100%;
		height: 100%;
		transition: all 0.3s ease-in-out;
		// background-color: rgba(0,0,0,.5);
		&>view{
			// position: absolute;
			// top: 50%;
			// left: 50%;
			color: #fff;
			margin: 100% 0 0 10%;
			width: 80%;
			height: 2.5rem;
			line-height: 2.5rem;
			border-radius: 0.3rem;
			background-color: rgba(0,0,0,.75);
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
	#firstCanvas{
		position: fixed;
		// right: 0;
		// top: 0;
		// border: 1px solid red;
		// width: 200rpx;
		// height: 200rpx;
		// background-color: rgba($color: #000000, $alpha: 0.5);
		// z-index: 99;
		// top: 0;
		// left: 0;
		// background: #150;
		
		// width: 150rpx;
		// height: 350rpx;
		top: -9999999999999rpx;
	}
	
	.loading {
	  height: 0.5rem;
	  margin: 0.2rem 0;
	  margin-left: 0.5rem;
	  display: flex;
	  align-items: center;
	  justify-content: center;
		  .loading-item {
			height: 0.5rem;
			width: 0.1rem;
			margin-right: 0.1rem;
		  }
		  
		  .loading-item:last-child {
		    margin-right: 0;
		  }
	}
	.loading-1 {
	  -webkit-animation: load-frame 1s infinite linear 0s;
	  -o-animation: load-frame 1s infinite linear 0s;
	  animation: load-frame 1s infinite linear 0s;
	  background-color: #fff;
	}
	.loading-2 {
	  -webkit-animation: load-frame 1s infinite linear 0.25s;
	  -o-animation: load-frame 1s infinite linear 0.25s;
	  animation: load-frame 1s infinite linear 0.25s;
	  background-color: #fff;
	}
	.loading-3 {
	  -webkit-animation: load-frame 1s infinite linear 0.5s;
	  -o-animation: load-frame 1s infinite linear 0.5s;
	  animation: load-frame 1s infinite linear 0.5s;
	  background-color: #fff;
	}
	.loading-4 {
	  -webkit-animation: load-frame 1s infinite linear 0.75s;
	  -o-animation: load-frame 1s infinite linear 0.75s;
	  animation: load-frame 1s infinite linear 0.75s;
	  background-color: #fff;
	}
	@keyframes load-frame {
	  0% {height: 0.5rem;}
	  50% {height: 0.125rem;}
	  100% {height: 0.5rem;}
	}
	@-webkit-keyframes load-frame {
	  0% {height: 0.5rem;}
	  50% {height: 0.125rem;}
	  100% {height: 0.5rem;}
	}
	 
</style>
